package com.nan.gbd.library.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Base64;

import com.nan.gbd.library.codec.configuration.Configuration;
import com.nan.gbd.library.sip.RecordBean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SpRecordUtils {

    private static SharedPreferences sp;
    private static Editor editor;

    public static final String KEY_RECORD_VIDEO_LIST = "record_video_list_key";

    private static SharedPreferences getSp() {
        if (sp == null) {
            sp = Configuration.get().getmContext().getSharedPreferences("helmet_sputils", Context.MODE_PRIVATE);
            editor = sp.edit();
        }
        return sp;
    }

    /**
     * 获取所有视频记录所对应的key
     *
     * @return
     */
    public static List<String> getVideoRecordKey() {
        String recordList = getString(SpRecordUtils.KEY_RECORD_VIDEO_LIST);
        List<String> stringList = new ArrayList<>();
        if (!TextUtils.isEmpty(recordList)) {
            String[] list = recordList.split(",");
            for (int i=0;i<list.length;i++){
                stringList.add(list[i]);
            }

        }
        return stringList;
    }

    public static boolean removeVideoRecordKey(String key) {
        if (TextUtils.isEmpty(key)) return false;
        String recordList = getString(SpRecordUtils.KEY_RECORD_VIDEO_LIST);
        if (!TextUtils.isEmpty(recordList)) {
            if (!recordList.contains(key)) {
                return true;
            }
        }
        List<String> stringList = getVideoRecordKey();
        if (stringList != null) {
            stringList.remove(key);
            removeKey(SpRecordUtils.KEY_RECORD_VIDEO_LIST);
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : stringList) {
                if (stringBuffer.length() == 0) {
                    stringBuffer.append(s);
                } else {
                    stringBuffer.append(",").append(s);
                }
            }
            putString(KEY_RECORD_VIDEO_LIST, stringBuffer.toString());
        }
        return true;
    }

    /**
     * 获取所有的视频录制记录实体
     *
     * @return
     */
    public static List<RecordBean> getRecordBeanList() {
        List<String> list = SpRecordUtils.getVideoRecordKey();
        List<RecordBean> beanList = new ArrayList<>();
        if (list.size() > 0) {
            for (String key : list) {
                RecordBean recordBean = SpRecordUtils.getObject(key);
                if (recordBean != null) {
                    beanList.add(recordBean);
                }
            }
        }
        return beanList;
    }

    /**
     * 保存新的视频录制记录
     *
     * @param videoKey
     */
    public static void putVideoRecordKey(String videoKey) {
        String videoKeyList = getString(SpRecordUtils.KEY_RECORD_VIDEO_LIST);
        StringBuffer stringBuffer = new StringBuffer();
        if (TextUtils.isEmpty(videoKeyList)) {
            stringBuffer.append(videoKey);
        } else {
            stringBuffer.append(videoKeyList).append(",").append(videoKey);
        }
        putString(KEY_RECORD_VIDEO_LIST, stringBuffer.toString());
    }


    /**
     * 删除对应的key
     *
     * @param key
     */
    public static void removeKey(String key) {
        SharedPreferences preferences = getSp();
        Editor editor = preferences.edit();
        editor.remove(key);
        editor.commit();
    }

    /**
     * 存入字符串
     *
     * @param key   字符串的键
     * @param value 字符串的值
     */
    public static void putString(String key, String value) {
        SharedPreferences preferences = getSp();
        //存入数据
        Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    /**
     * 获取字符串
     *
     * @param key 字符串的键
     * @return 得到的字符串
     */
    public static String getString(String key) {
        SharedPreferences preferences = getSp();
        return preferences.getString(key, "");
    }

    /**
     * 获取字符串
     *
     * @param key   字符串的键
     * @param value 字符串的默认值
     * @return 得到的字符串
     */
    public static String getString(String key, String value) {
        SharedPreferences preferences = getSp();
        return preferences.getString(key, value);
    }

    /**
     * 保存布尔值
     *
     * @param key   键
     * @param value 值
     */
    public static void putBoolean(String key, boolean value) {
        SharedPreferences sp = getSp();
        Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * 获取布尔值
     *
     * @param key      键
     * @param defValue 默认值
     * @return 返回保存的值
     */
    public static boolean getBoolean(String key, boolean defValue) {
        SharedPreferences sp = getSp();
        return sp.getBoolean(key, defValue);
    }

    /**
     * 保存long值
     *
     * @param key   键
     * @param value 值
     */
    public static void putLong(String key, long value) {
        SharedPreferences sp = getSp();
        Editor editor = sp.edit();
        editor.putLong(key, value);
        editor.commit();
    }

    /**
     * 获取long值
     *
     * @param key      键
     * @param defValue 默认值
     * @return 保存的值
     */
    public static long getLong(String key, long defValue) {
        SharedPreferences sp = getSp();
        return sp.getLong(key, defValue);
    }

    /**
     * 保存int值
     *
     * @param key   键
     * @param value 值
     */
    public static void putInt(String key, int value) {
        SharedPreferences sp = getSp();
        Editor editor = sp.edit();
        editor.putInt(key, value);
        editor.commit();
    }

    /**
     * 获取long值
     *
     * @param key      键
     * @param defValue 默认值
     * @return 保存的值
     */
    public static int getInt(String key, int defValue) {
        SharedPreferences sp = getSp();
        return sp.getInt(key, defValue);
    }

    /**
     * 保存对象
     *
     * @param key 键
     * @param obj 要保存的对象（Serializable的子类）
     * @param <T> 泛型定义
     */
    public static <T extends Serializable> void putObject(String key, T obj) {
        try {
            put(key, obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取对象
     *
     * @param key 键
     * @param <T> 指定泛型
     * @return 泛型对象
     */
    public static <T extends Serializable> T getObject(String key) {
        try {
            return (T) get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存List
     *
     * @param tag
     * @param datalist
     */
//    public <T> void setDataList(String tag, List<T> datalist) {
//        if (null == datalist || datalist.size() <= 0)
//            return;
//        JSONArray jsonObject = new JSONArray();
//        Gson gson = new Gson();
//        //转换成json数据，再保存
//        String strJson = gson.toJson(datalist);
//        editor.clear();
//        editor.putString(tag, strJson);
//        editor.commit();
//
//    }

    /**
     * 获取List
     *
     * @param tag
     * @return
     */
//    public <T> List<T> getDataList(String tag) {
//        List<T> datalist = new ArrayList<>();
//        String strJson = sp.getString(tag, null);
//        if (null == strJson) {
//            return datalist;
//        }
//        Gson gson = new Gson();
//        datalist = gson.fromJson(strJson, new TypeToken<List<T>>() {
//        }.getType());
//        return datalist;
//
//    }

    /**
     * 存储Map集合
     *
     * @param key 键
     * @param map 存储的集合
     * @param <K> 指定Map的键
     * @param <T> 指定Map的值
     */

//    public <K, T> void setMap(String key, Map<K, T> map) {
//        if (map == null || map.isEmpty() || map.size() < 1) {
//            return;
//        }
//
//        Gson gson = new Gson();
//        String strJson = gson.toJson(map);
//        editor.clear();
//        editor.putString(key, strJson);
//        editor.commit();
//    }

    /**
     * 获取Map集合
     */
//    public <K, T> Map<K, T> getMap(String key) {
//        Map<K, T> map = new HashMap<>();
//        String strJson = sp.getString(key, null);
//        if (strJson == null) {
//            return map;
//        }
//        Gson gson = new Gson();
//        map = gson.fromJson(strJson, new TypeToken<Map<K, T>>() {
//        }.getType());
//        return map;
//    }

    /**
     * 存储对象
     */
    private static void put(String key, Object obj)
            throws IOException {
        if (obj == null) {//判断对象是否为空
            return;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        // 将对象放到OutputStream中
        // 将对象转换成byte数组，并将其进行base64编码
        String objectStr = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
        baos.close();
        oos.close();

        putString(key, objectStr);
    }

    /**
     * 获取对象
     */
    private static Object get(String key) throws IOException, ClassNotFoundException {
        String wordBase64 = getString(key);
        // 将base64格式字符串还原成byte数组
        if (TextUtils.isEmpty(wordBase64)) { //不可少，否则在下面会报java.io.StreamCorruptedException
            return null;
        }
        byte[] objBytes = Base64.decode(wordBase64.getBytes(), Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        // 将byte数组转换成product对象
        Object obj = ois.readObject();
        bais.close();
        ois.close();
        return obj;
    }


}
